/**
 * Messages
 */

$(document).ready(function(){
});



/**
 * Получение и вызов метода обработки числа сообщений (вызывается периодески)
 */
function messagesGetCountNew(area, id){
	var callback = function(data){
		var idView = 'idCountNew'+area;
		var response = (typeof data == 'undefined' || data.length==0) ? {} : eval( "(" + data + ")" );
		if ( response.gages && response.cnt>0 ){
			$('#'+idView).removeClass('link-message').removeClass('brown');
			$('#'+idView).addClass('link-new-message').addClass('red');
		}else{
			$('#'+idView).removeClass('link-new-message').removeClass('red');
			$('#'+idView).addClass('link-message').addClass('brown');
		}
		$('#'+idView).html(response.cnt);
	}
	$.post("/common/cntnewmsgs.php", {clientid: id}, callback, "json");
	msg_timer = setTimeout( function(){messagesGetCountNew(area, id)}, 6000 );
}



/**
 * Открытие дива с формой отправки сообщения
 */
function messagesOpenSendDiv(area, dest, topic, env, isError){
	if ( typeof isError == 'undefined' ) isError = 0;

	var el1 = $('#sendFormDESTINATION_ID'+area);
	if(el1){ el1.val(dest ? dest : "") }

	var el2 = $('#sendFormTOPIC_ID'+area);
	if(el2){ el2.val(topic ? topic : "") }

	var el3 = $('#sendFormEVENT_TYPE'+area);
	if(el3){
		var msg_text = "";
		if ( env ){
			el3.val(env);
			if(env==1){ //join to team request
				msg_text = Dictionary.translate('lang_messages_team_request');
			}
			if(env==2){ //kick off player from team
				msg_text = Dictionary.translate('lang_messages_kick_from_team');
			}
			if(env==3){ //join to friend request
				msg_text = Dictionary.translate('lang_messages_friend_request');
			}
			if(env==4){ //invite to team
				msg_text = Dictionary.translate('lang_messages_team_invite');
			}
			if(env==5){ //kick off player from friends
				msg_text = Dictionary.translate('lang_messages_kick_from_friends');
			}
		}else{
			el3.val(0);
		}
		$('#sendFormBODY'+area).html(msg_text);
	}
	if ( isError ){
		$('#sendFormDiv'+area).hide();
		$('#sendResult'+area).show();
	}else{
		$('#sendResult'+area).hide();
		$('#sendFormDiv'+area).show();
	}
	$('#id_openMessagePopup'+area).click();
}

/**
 * Открытие дива с формой отправки сообщения
 */
function showLoader(fComplete){
	var loader = '<img src="/common/img/load.gif" />';
	$.fancybox({content:loader, showCloseButton:false, onComplete:fComplete});
}

/**
 * Открытие дива с формой отправки сообщения
 */
function getFootballer(id){
	var result = $.ajax({
		type: "post",
		url: '/common/footballer.php?action=get&site_id='+env.site_id+'&page_id='+env.page_id+'&lang_id='+env.lang_id+'&version='+env.version+'&id='+id+'',
		async: false
	}).responseText;

	return (typeof result == 'undefined' || result.length==0) ? {} : eval( "(" + result + ")" );
}

/**
 * Открытие дива с формой отправки сообщения
 */
function messagesOpenSendDiv2(area, dest, topic, env, isError){
	var fComplete = function(){
		if ( typeof isError == 'undefined' ) isError = 0;

		var msg = messageMakeBody(env);
		var sendForm = messageMakeSendForm(dest, topic, env, msg, isError);

		$.fancybox.hideActivity();
		$.fancybox({content:sendForm});
	}
	showLoader(fComplete);
	
	/*if ( isError ){
		$('#messageSendFormDiv').hide();
		$('#messageResult').show();
	}else{
		$('#messageResult').hide();
		$('#messageSendFormDiv').show();
	}
	$('#id_openMessagePopup'+area).click();
	*/
	
}

/**
 * Формирование html-кода формы отправки сообщения
 */
function messageMakeSendForm(dest, topic, env, msg, isError){
	var dest_param = getFootballer(dest);
	var form = '';
	form += '<div id="messageSendDiv">';
	form += '<p id="messageResult" style="margin:0;"'+(isError ? '' : ' class="hidden"')+'></p>';
	form += '<div id="messageSendFormDiv"'+(!isError ? '' : ' class="hidden"')+'>';
	form += '<form action="" method="POST" name="messageSendForm" onsubmit="return messageSend(this);">';
	form += '<h2>'+Dictionary.translate('lang_messages_send_message')+'</h2>';
	form += '<input type="hidden" name="add" value="1">';
	form += '<input type="hidden" name="SEND" value="1">';
	form += '<input type="hidden" name="TOPIC_ID" value="'+(topic ? topic : '')+'">';
	form += '<input type="hidden" name="EVENT_TYPE" value="'+(env ? env : '')+'">';
	form += '<input type="hidden" name="DESTINATION_ID" value="'+(dest ? dest : '')+'">';
	//form += '<input type="hidden" name="DESTINATION" value=""';
	if ( dest ){
		form += '<div class="group-items clearfix">';
		form += '<label for="messageSendFormBODY">'+Dictionary.translate('lang_messages_whom')+' </label>';
		form += '<a href="'+dest_param.url+'" title="'+dest_param.name+'">'+dest_param.name+'</a>';
		form += '</div>';
	}
	form += '<div class="group-items clearfix">';
	form += '<label for="messageSendFormBODY">'+Dictionary.translate('lang_messages_message')+' <span class="required">*</span></label>';
	form += '<textarea id="messageSendFormBODY" class="form_input" cols="30" style="width:95%" rows="8" name="_nonempty_BODY" title="'+Dictionary.translate('lang_messages_message')+'">'+(msg ? msg : '')+'</textarea>';
	form += '</div>';
	form += '<div class="group-items">';
	form += '<input type="submit" value="'+Dictionary.translate('lang_messages_button_send')+'" class="input_button" />';
	form += '</div>';
	form += '</form>';
	form += '</div>';
	form += '</div>';
	return form;
}

/**
 * Формирование тела сообщения для различных событий
 */
function messageMakeBody(env){
	if ( !env )
		return '';

	var msg = '';
	if(env==1){ //join to team request
		msg = Dictionary.translate('lang_messages_team_request');
	}
	if(env==2){ //kick off player from team
		msg = Dictionary.translate('lang_messages_kick_from_team');
	}
	if(env==3){ //join to friend request
		msg = Dictionary.translate('lang_messages_friend_request');
	}
	if(env==4){ //invite to team
		msg = Dictionary.translate('lang_messages_team_invite');
	}
	if(env==5){ //kick off player from friends
		msg = Dictionary.translate('lang_messages_kick_from_friends');
	}
	return msg;
}


/**
 * Вывод информационного сообщения
 */
function messageAlert(msg){
	alert(msg);
}



/**
 * Обработка ошибки ajax
 */
function messageAjaxError(response){
	if (response.error == 'impossibly'){
		messageAlert(Dictionary.translate('lang_messages_error_impossibly'));
	}else if (response.error == 'empty_destination'){
		messageAlert(Dictionary.translate('lang_messages_error_empty_destination'));
	}else if (response.error == 'yourself'){
		messageAlert(Dictionary.translate('lang_messages_error_yourself'));
	}else if (response.error == 'ignored'){
		messageAlert(Dictionary.translate('lang_messages_error_ignored'));
	}else if (response.error == 'dubleevent'){
		messageAlert(Dictionary.translate('lang_messages_error_dubleevent'));
	}else if (response.error == 'me_in_team'){
		messageAlert(Dictionary.translate('lang_messages_error_me_in_team'));
	}else if (response.error == 'he_in_team'){
		messageAlert(Dictionary.translate('lang_messages_error_he_in_team'));
	}else{
		messageAlert(Dictionary.translate('lang_messages_error_other')+(response.body?':\r\n'+response.body:''));
	}
}

/**
 * Отправка сообщения
 */
function messageSend(form){
	if ( !CheckMandatoryFields($(form).attr('name')) )
		return false;

	var data = {
		add: jQuery.trim(form.elements['add'].value),
		SEND: jQuery.trim(form.elements['SEND'].value),
		TOPIC_ID: jQuery.trim(form.elements['TOPIC_ID'].value),
		EVENT_TYPE: jQuery.trim(form.elements['EVENT_TYPE'].value),
		DESTINATION_ID: jQuery.trim(form.elements['DESTINATION_ID'].value),
		//DESTINATION: jQuery.trim(form.elements['DESTINATION'].value),
		BODY: jQuery.trim(form.elements['BODY'].value)
	}
	var callback = function(data){
		var response = (typeof data == 'undefined' || data.length==0) ? {} : eval( "(" + data + ")" );
		if (response.status){
			$.fancybox.hideActivity();
			$.fancybox({content:Dictionary.translate('lang_messages_message_sent')});
		}else{
			messageAjaxError(response);
		}
	}
	var res = $.ajax({
		url: '/common/messages.php?action=send&site_id='+env.site_id+'&page_id='+env.page_id+'&lang_id='+env.lang_id+'&version='+env.version+'',
		cache: false,
		data: data,
		success:function(data){
			callback(data)
		}
	}); 	
	return false;
}

/**
 * Отображение сообщения о результате отправки (показывается только один раз)
 */
function messagesShowStateMessage(area, lang){
	if ( !dlgFlagMsg )
		return dlgFlagMsg;

	$('#sendFormBODY'+area).focus();
	var send_msg = messagesGetStateMessage();
	if ( send_msg != '' ){
		dlgFlagMsg = 0;
		$('#sendResult'+area).html(send_msg);
		$('#id_openMessagePopup'+area).click();
	};
	return dlgFlagMsg;
}




/**
 * Открытие дива с формой отправки сообщения команде
 */
function messagesOpenSendSelfTeamDiv(area, lang, env, isError){
	if ( typeof isError == 'undefined' ) isError = 0;
	$('#sendFormSelfTeamEVENT_TYPE'+area).val(env);
	if ( isError ){
		$('#sendFormDivSelfTeam'+area).hide();
		$('#sendResultSelfTeam'+area).show();
	}else{
		$('#sendResultSelfTeam'+area).hide();
		$('#sendFormDivSelfTeam'+area).show();
	}
	$('#id_openMessagePopupSelfTeam'+area).click();
}

/**
 * 
 */
function messagesChangeSelectionPlayer(area, lang, e,id){
	if ( e.className == 'selected' ){
		$(e).removeClass('selected');
		$(e).addClass('not-selected');
	}else{
		$(e).removeClass('not-selected');
		$(e).addClass('selected');
	}
	$('#sendFormDESTINATION_IDS'+area+'_'+id+'').attr('checked',(e.className == 'selected' ? 'checked' : ''));
}


/**
 * Отображение сообщения о результате отправки команде (показывается только один раз)
 */
function messagesShowStateMessageSelfTeam(area, lang){
	if ( !dlgFlagMsgSelfTeam )
		return dlgFlagMsgSelfTeam;

	$('#sendFormSelfTeamBODY'+area).focus();
	var send_msg = messagesGetStateMessageSelfTeam();
	if ( send_msg != '' ){
		dlgFlagMsgSelfTeam = 0;
		$('#sendResultSelfTeam'+area).html(send_msg);
		messagesOpenSendSelfTeamDiv(area, lang, 0,1);
		$('#id_openMessagePopupSelfTeam'+area).click();
	};
	return dlgFlagMsgSelfTeam;
}


